<?php

if (!function_exists('format_price')) {
    /**
     * 格式化价格
     */
    function format_price($price, $currency = '¥'): string
    {
        return $currency . number_format($price, 2);
    }
}

if (!function_exists('format_date')) {
    /**
     * 格式化日期
     */
    function format_date($date, $format = 'Y-m-d H:i:s'): string
    {
        if (!$date) {
            return '';
        }
        
        if (is_string($date)) {
            $date = \Carbon\Carbon::parse($date);
        }
        
        return $date->format($format);
    }
}

if (!function_exists('format_relative_time')) {
    /**
     * 格式化相对时间
     */
    function format_relative_time($date): string
    {
        if (!$date) {
            return '';
        }
        
        if (is_string($date)) {
            $date = \Carbon\Carbon::parse($date);
        }
        
        return $date->diffForHumans();
    }
}

if (!function_exists('generate_order_number')) {
    /**
     * 生成订单号
     */
    function generate_order_number(): string
    {
        return date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
    }
}

if (!function_exists('generate_sku')) {
    /**
     * 生成SKU
     */
    function generate_sku(string $prefix = 'SKU'): string
    {
        return $prefix . strtoupper(uniqid());
    }
}

if (!function_exists('generate_slug')) {
    /**
     * 生成URL友好的slug
     */
    function generate_slug(string $text): string
    {
        $text = preg_replace('/[^\p{L}\p{N}\s-]/u', '', $text);
        $text = preg_replace('/[\s-]+/', '-', $text);
        return strtolower(trim($text, '-'));
    }
}

if (!function_exists('mask_phone')) {
    /**
     * 脱敏手机号
     */
    function mask_phone(string $phone): string
    {
        if (strlen($phone) < 7) {
            return $phone;
        }
        
        return substr($phone, 0, 3) . '****' . substr($phone, -4);
    }
}

if (!function_exists('mask_email')) {
    /**
     * 脱敏邮箱
     */
    function mask_email(string $email): string
    {
        $parts = explode('@', $email);
        if (count($parts) !== 2) {
            return $email;
        }
        
        $username = $parts[0];
        $domain = $parts[1];
        
        if (strlen($username) <= 2) {
            return $username . '@' . $domain;
        }
        
        $maskedUsername = substr($username, 0, 1) . str_repeat('*', strlen($username) - 2) . substr($username, -1);
        return $maskedUsername . '@' . $domain;
    }
}

if (!function_exists('mask_card_number')) {
    /**
     * 脱敏银行卡号
     */
    function mask_card_number(string $cardNumber): string
    {
        if (strlen($cardNumber) < 8) {
            return $cardNumber;
        }
        
        return substr($cardNumber, 0, 4) . str_repeat('*', strlen($cardNumber) - 8) . substr($cardNumber, -4);
    }
}

if (!function_exists('format_file_size')) {
    /**
     * 格式化文件大小
     */
    function format_file_size(int $bytes): string
    {
        $units = ['B', 'KB', 'MB', 'GB', 'TB'];
        
        for ($i = 0; $bytes > 1024 && $i < count($units) - 1; $i++) {
            $bytes /= 1024;
        }
        
        return round($bytes, 2) . ' ' . $units[$i];
    }
}

if (!function_exists('get_file_extension')) {
    /**
     * 获取文件扩展名
     */
    function get_file_extension(string $filename): string
    {
        return strtolower(pathinfo($filename, PATHINFO_EXTENSION));
    }
}

if (!function_exists('is_image_file')) {
    /**
     * 判断是否为图片文件
     */
    function is_image_file(string $filename): bool
    {
        $imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp', 'svg'];
        $extension = get_file_extension($filename);
        return in_array($extension, $imageExtensions);
    }
}

if (!function_exists('is_video_file')) {
    /**
     * 判断是否为视频文件
     */
    function is_video_file(string $filename): bool
    {
        $videoExtensions = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'webm', 'mkv'];
        $extension = get_file_extension($filename);
        return in_array($extension, $videoExtensions);
    }
}

if (!function_exists('is_document_file')) {
    /**
     * 判断是否为文档文件
     */
    function is_document_file(string $filename): bool
    {
        $documentExtensions = ['pdf', 'doc', 'docx', 'txt', 'rtf', 'odt'];
        $extension = get_file_extension($filename);
        return in_array($extension, $documentExtensions);
    }
}

if (!function_exists('truncate_string')) {
    /**
     * 截断字符串
     */
    function truncate_string(string $string, int $length = 100, string $suffix = '...'): string
    {
        if (mb_strlen($string) <= $length) {
            return $string;
        }
        
        return mb_substr($string, 0, $length) . $suffix;
    }
}

if (!function_exists('clean_html')) {
    /**
     * 清理HTML标签
     */
    function clean_html(string $html): string
    {
        return strip_tags($html);
    }
}

if (!function_exists('generate_random_string')) {
    /**
     * 生成随机字符串
     */
    function generate_random_string(int $length = 10, bool $includeNumbers = true, bool $includeSymbols = false): string
    {
        $characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        
        if ($includeNumbers) {
            $characters .= '0123456789';
        }
        
        if ($includeSymbols) {
            $characters .= '!@#$%^&*()_+-=[]{}|;:,.<>?';
        }
        
        $string = '';
        for ($i = 0; $i < $length; $i++) {
            $string .= $characters[rand(0, strlen($characters) - 1)];
        }
        
        return $string;
    }
}

if (!function_exists('generate_uuid')) {
    /**
     * 生成UUID
     */
    function generate_uuid(): string
    {
        return \Illuminate\Support\Str::uuid()->toString();
    }
}

if (!function_exists('array_get_nested')) {
    /**
     * 获取嵌套数组值
     */
    function array_get_nested(array $array, string $key, $default = null)
    {
        $keys = explode('.', $key);
        $value = $array;
        
        foreach ($keys as $k) {
            if (!is_array($value) || !array_key_exists($k, $value)) {
                return $default;
            }
            $value = $value[$k];
        }
        
        return $value;
    }
}

if (!function_exists('array_set_nested')) {
    /**
     * 设置嵌套数组值
     */
    function array_set_nested(array &$array, string $key, $value): void
    {
        $keys = explode('.', $key);
        $current = &$array;
        
        foreach ($keys as $k) {
            if (!is_array($current)) {
                $current = [];
            }
            if (!array_key_exists($k, $current)) {
                $current[$k] = [];
            }
            $current = &$current[$k];
        }
        
        $current = $value;
    }
}

if (!function_exists('array_flatten')) {
    /**
     * 扁平化数组
     */
    function array_flatten(array $array, int $depth = INF): array
    {
        $result = [];
        
        foreach ($array as $item) {
            if (is_array($item) && $depth > 0) {
                $result = array_merge($result, array_flatten($item, $depth - 1));
            } else {
                $result[] = $item;
            }
        }
        
        return $result;
    }
}

if (!function_exists('array_group_by')) {
    /**
     * 按键分组数组
     */
    function array_group_by(array $array, $key): array
    {
        $result = [];
        
        foreach ($array as $item) {
            $groupKey = is_callable($key) ? $key($item) : (is_array($item) ? $item[$key] : $item->$key);
            $result[$groupKey][] = $item;
        }
        
        return $result;
    }
}

if (!function_exists('validate_chinese_phone')) {
    /**
     * 验证中国手机号
     */
    function validate_chinese_phone(string $phone): bool
    {
        return preg_match('/^1[3-9]\d{9}$/', $phone);
    }
}

if (!function_exists('validate_chinese_id_card')) {
    /**
     * 验证中国身份证号
     */
    function validate_chinese_id_card(string $idCard): bool
    {
        return preg_match('/^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/', $idCard);
    }
}

if (!function_exists('validate_email')) {
    /**
     * 验证邮箱
     */
    function validate_email(string $email): bool
    {
        return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
    }
}

if (!function_exists('validate_url')) {
    /**
     * 验证URL
     */
    function validate_url(string $url): bool
    {
        return filter_var($url, FILTER_VALIDATE_URL) !== false;
    }
}

if (!function_exists('get_client_ip')) {
    /**
     * 获取客户端IP
     */
    function get_client_ip(): string
    {
        $ipKeys = ['HTTP_X_FORWARDED_FOR', 'HTTP_X_REAL_IP', 'HTTP_CLIENT_IP', 'REMOTE_ADDR'];
        
        foreach ($ipKeys as $key) {
            if (!empty($_SERVER[$key])) {
                $ips = explode(',', $_SERVER[$key]);
                $ip = trim($ips[0]);
                if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
                    return $ip;
                }
            }
        }
        
        return $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
    }
}

if (!function_exists('get_user_agent')) {
    /**
     * 获取用户代理
     */
    function get_user_agent(): string
    {
        return $_SERVER['HTTP_USER_AGENT'] ?? '';
    }
}

if (!function_exists('is_mobile_device')) {
    /**
     * 判断是否为移动设备
     */
    function is_mobile_device(): bool
    {
        $userAgent = get_user_agent();
        $mobileKeywords = ['Mobile', 'Android', 'iPhone', 'iPad', 'iPod', 'BlackBerry', 'Windows Phone'];
        
        foreach ($mobileKeywords as $keyword) {
            if (stripos($userAgent, $keyword) !== false) {
                return true;
            }
        }
        
        return false;
    }
}

if (!function_exists('get_browser_name')) {
    /**
     * 获取浏览器名称
     */
    function get_browser_name(): string
    {
        $userAgent = get_user_agent();
        
        if (strpos($userAgent, 'Chrome') !== false) {
            return 'Chrome';
        } elseif (strpos($userAgent, 'Firefox') !== false) {
            return 'Firefox';
        } elseif (strpos($userAgent, 'Safari') !== false) {
            return 'Safari';
        } elseif (strpos($userAgent, 'Edge') !== false) {
            return 'Edge';
        } elseif (strpos($userAgent, 'Opera') !== false) {
            return 'Opera';
        } else {
            return 'Unknown';
        }
    }
}

if (!function_exists('get_os_name')) {
    /**
     * 获取操作系统名称
     */
    function get_os_name(): string
    {
        $userAgent = get_user_agent();
        
        if (strpos($userAgent, 'Windows') !== false) {
            return 'Windows';
        } elseif (strpos($userAgent, 'Mac') !== false) {
            return 'macOS';
        } elseif (strpos($userAgent, 'Linux') !== false) {
            return 'Linux';
        } elseif (strpos($userAgent, 'Android') !== false) {
            return 'Android';
        } elseif (strpos($userAgent, 'iOS') !== false) {
            return 'iOS';
        } else {
            return 'Unknown';
        }
    }
}

if (!function_exists('calculate_distance')) {
    /**
     * 计算两点间距离（公里）
     */
    function calculate_distance(float $lat1, float $lon1, float $lat2, float $lon2): float
    {
        $earthRadius = 6371; // 地球半径（公里）
        
        $dLat = deg2rad($lat2 - $lat1);
        $dLon = deg2rad($lon2 - $lon1);
        
        $a = sin($dLat / 2) * sin($dLat / 2) +
             cos(deg2rad($lat1)) * cos(deg2rad($lat2)) *
             sin($dLon / 2) * sin($dLon / 2);
        
        $c = 2 * atan2(sqrt($a), sqrt(1 - $a));
        
        return $earthRadius * $c;
    }
}

if (!function_exists('format_duration')) {
    /**
     * 格式化时长
     */
    function format_duration(int $seconds): string
    {
        $hours = floor($seconds / 3600);
        $minutes = floor(($seconds % 3600) / 60);
        $seconds = $seconds % 60;
        
        if ($hours > 0) {
            return sprintf('%d小时%d分钟%d秒', $hours, $minutes, $seconds);
        } elseif ($minutes > 0) {
            return sprintf('%d分钟%d秒', $minutes, $seconds);
        } else {
            return sprintf('%d秒', $seconds);
        }
    }
}

if (!function_exists('convert_to_pinyin')) {
    /**
     * 中文转拼音（需要安装拼音扩展）
     */
    function convert_to_pinyin(string $chinese): string
    {
        // 这里需要安装拼音扩展，如 overtrue/pinyin
        // 暂时返回原字符串
        return $chinese;
    }
}

if (!function_exists('is_workday')) {
    /**
     * 判断是否为工作日
     */
    function is_workday($date = null): bool
    {
        $date = $date ? \Carbon\Carbon::parse($date) : now();
        return $date->isWeekday();
    }
}

if (!function_exists('get_weekday_name')) {
    /**
     * 获取星期名称
     */
    function get_weekday_name($date = null): string
    {
        $date = $date ? \Carbon\Carbon::parse($date) : now();
        $weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
        return $weekdays[$date->dayOfWeek];
    }
}
